<template lang="pug">
div
  FixedScroll(:minusBottomHeight="minusBottomHeight")
    div(slot="fixed")
      PageHeader(:pageTitle="pageTitle")
        div(
            slot="right"
            @click="save"
            :class="{'save-disabled': !saveEnabled, active: saveEnabled}"
            ) 保存

      ScanSearch(
          placeholder="序列号"
          :initSearchValue="searchValue"
          @search="search"
          @scan="search"
          )

    ColoredTable.table(
        slot="scroll"
        :headList="headList"
        :body="barcodeBody"
        :statusMap="statusMap"
        :isLoading="isLoading"
        @delete-row="deleteRow"
        )

</template>

<script>
import api from "$api"
import util from "$util"

export default {
  props: {
    forceUpdate: {
      type: Boolean,
      default: false,
    },
    minusBottomHeight: {
      type: Number,
      default: 0,
    },
    pageTitle: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      searchValue: "",
      isLoading: false,

      codeMap: {},
      statusMap: {},
      saveEnabled: false,
      saved: false,

      loading: {
        search: false,
        save: false,
      },

      headList: [
        { field: "delete-row", title: "", checked: true },
        { field: "BarcodeData", title: "序列号", checked: true },
        { field: "PartNo", title: "物料号", checked: true },
        { field: "SupplierNum", title: "供应商", checked: true },
        { field: "AvailbleNum", title: "库存", checked: true },
        { field: "StorgelocationCode", title: "实体仓库", checked: true },
        { field: "WmNo", title: "逻辑仓库", checked: true },
        { field: "ZoneNo", title: "存储区", checked: true },
        { field: "PartType", title: "物料类型", checked: true },
        { field: "BatchNo", title: "批次", checked: true },
      ],

      barcodeBody: {
        list: [],
      },
    }
  },
  computed: {
    op() {
      let FrozenType = "Frozen"
      if (this.pageTitle === "解封") {
        FrozenType = "Unseal"
      }
      return FrozenType
    },
  },
  watch: {
    forceUpdate(v) {
      if (v) {
        this.registerScanner()
        this.$forceUpdate()
      }
    }
  },

  methods: {
    async search(value) {
      if (this.loading.search) {
        return
      }
      if (value === "") {
        return
      }
      if (this.saved) {
        this.barcodeBody.list = []
        this.codeMap = {}
        this.saved = false
      }
      if (this.codeMap[value]) {
        return
      }

      this.loading.search = true
      try {
        let data = await api.StockPackGetInfo({
          BarcodeData: value,
          FrozenType: this.op,
        })

        // check
        if (this.barcodeBody.list.length > 0) {
          let item = this.barcodeBody.list[0]
          let errmsg = ""
          if (data.StorgelocationCode !== item.StorgelocationCode) {
            errmsg = `实体仓库${item.StorgelocationCode}`
          } else if (data.WmNo !== item.WmNo) {
            errmsg = `逻辑仓库${item.WmNo}`
          } else if (data.ZoneNo !== item.ZoneNo) {
            errmsg = `存储区${item.ZoneNo}`
          }
          if (errmsg) {
            util.Alert(`此序列号不在${errmsg}中`)
            return
          }
        }

        let enumList = api.Enum.StockMove.PartType.value
        data.PartType = enumList[data.PartType]
        this.barcodeBody.list.push(data)
        if (this.barcodeBody.list.length > 0 && !this.saveEnabled) {
          this.saveEnabled = true
        }

        data["delete-row"] = true
        this.codeMap[value] = true
        this.statusMap[value] = util.STATUS_OK
      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.search = false
      }
    },

    async save() {
      if (this.loading.save || !this.saveEnabled) {
        return
      }

      let enumMap = api.Enum.StockMove.PartType.value
      let valueMap = {}
      for (let k in enumMap) {
        valueMap[enumMap[k]] = k
      }
      let newList = this.copyList(this.barcodeBody.list)
      for (let item of newList) {
        item.PartType = valueMap[item.PartType]
      }

      this.loading.save = true
      try {
        await api.StockPackSave({
          FrozenType: this.op,
          stocksList: newList,
        })
        this.saveEnabled = false
        this.saved = true
        util.Toast("保存成功")
      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.save = false
      }
    },

    copyList(list) {
      let newList = new Array(list.length)
      let i = 0
      for (let item of list) {
        let newItem = {
          ...item,
        }
        newList[i] = newItem
        i++
      }
      return newList
    },

    deleteRow(barcode) {
      let bodyIndex = -1
      for (let [i, item] of this.barcodeBody.list.entries()) {
        if (item.BarcodeData === barcode) {
          bodyIndex = i
          break
        }
      }
      if (bodyIndex >= 0) {
        this.barcodeBody.list.splice(bodyIndex, 1)
        this.codeMap[barcode] = false
        if (this.barcodeBody.list.length === 0) {
          this.saveEnabled = false
        }
      }
    },

    registerScanner() {
      util.registerScanner((data) => {
        this.searchValue = data
        this.search(data)
      })
    },
  },

  created() {
    if (this.pageTitle === "封存") {
      this.registerScanner()
    }
  },
}
</script>

<style lang="stylus" scoped>

.save-disabled
  color: grey500

.active:active
  active-color()

.table
  scan-table()

</style>
